`
echo "${USER_INPUT} is a file"
3 elif [[ -d "${USER_INPUT}" ]]; then
echo "${USER_INPUT} is a directory"
else
4 echo "${USER_INPUT} is not a file or a directory"
fi
Listing 2-7
Using if and elif statements
We begin with an if statement that checks whether the variable
USER_INPUT is null 1. This allows us to exit the script early using exit 1 if we
receive no command line arguments from the user. We then begin a second if
condition that uses the file test operator to check whether the input is a file 2.
Below this condition, we use elif to test whether the argument is a directory 3.
This condition won’t be tested unless the file test fails. If neither of these
conditions is true, the script responds that the argument is neither a file nor a
directory 4.
This script is available at https://github.com/dolevf/Black-Hat-
Bash/blob/master/ch02/if_elif.sh.
Functions
Functions help us reuse blocks of code so we can avoid repeating them. They
allow us to run multiple commands and other bash code together by simply
entering the function’s name. To define a new function, enter a name for it,
followed by parentheses (). Then place the code you would like the function to
run within curly brackets {}:
#!/bin/bash
say_name(){
echo "Black Hat Bash"
}
Here, we define a function called say_name that executes a single echo
command. To call a function, simply enter its name:
say_name
If the function is not called, the commands within it won’t run.
Returning Values
Like commands and their exit statuses, functions can return values using the
return keyword. If there is no return statement, the function will return the
code of the last command it ran. For example, the function in Listing 2-8 returns a
different value based on whether the current user is root or not:
#!/bin/bash
1 check_if_root(){
Black Hat Bash (Early Access) © 2023 by Dolev Farhi and Nick Aleks